package com.szgr.baoyin.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.InvoiceListAdapter;
import com.szgr.baoyin.model.InvoiceListItem;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.RLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InvoiceActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private String vat_hash;
    private List<InvoiceListItem> data;
    private InvoiceListAdapter listAdapter;
    private boolean isFromCard;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 33:
                    noRecord.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.GONE);
                    break;
                case 34:
                    noRecord.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };
    private ListView listView;
    private View noRecord;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_invoice);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("发票");
    }

    @Override
    public void initView() {
        findViewById(R.id.invoice_add).setOnClickListener(this);

        Intent intent = getIntent();
        if(intent != null && intent.hasExtra("vat_hash")){
            vat_hash = intent.getStringExtra("vat_hash");
        }
        if(intent != null && intent.hasExtra("isFromCard")){
            isFromCard = intent.getBooleanExtra("isFromCard",false);
        }

        data = new ArrayList<>();
        listView = (ListView) findViewById(R.id.invoice_list_view);
        listAdapter = new InvoiceListAdapter(this, data,this);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(this);

        noRecord = findViewById(R.id.no_record);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isFromCard) {
            getInvoice1();
        }else{
            getInvoice();
        }
    }

    private void getInvoice1() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_CARD_INV,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-- invoice--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray invoice_list = datas.getJSONArray("invoice_list");
                            Gson gson = new Gson();
                            data = gson.fromJson(invoice_list.toString(),new TypeToken<List<InvoiceListItem>>(){}.getType());
                            if(data != null && data.size() == 0){
                                mHandler.obtainMessage(33).sendToTarget();
                            }
                            listAdapter.setData(data);
                            mHandler.obtainMessage(34).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    private void getInvoice() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_LOAD_INVOICE,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-- invoice--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONArray datas = jsonObject.getJSONArray("datas");
                            Gson gson = new Gson();
                            data = gson.fromJson(datas.toString(),new TypeToken<List<InvoiceListItem>>(){}.getType());
                            if(data != null && data.size() == 0){
                                mHandler.obtainMessage(33).sendToTarget();
                            }
                            listAdapter.setData(data);
                            mHandler.obtainMessage(34).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("vat_hash",vat_hash);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.invoice_add:
                startActivity(new Intent(this,InvoiceAddActivity.class));
                break;
            case R.id.item_delete:
                int tag = (int) v.getTag();
                InvoiceListItem invoiceListItem = data.get(tag);

                deleteInv(invoiceListItem.getInv_id());
                break;
        }
    }

    private void deleteInv(final String id) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_DELETE_INV,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        RLog.s("---delete-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray invoice_list = datas.getJSONArray("invoice_list");
                            Gson gson = new Gson();
                            data = gson.fromJson(invoice_list.toString(),new TypeToken<List<InvoiceListItem>>(){}.getType());
                            if(data != null && data.size() == 0){
                                mHandler.obtainMessage(33).sendToTarget();
                            }
                            listAdapter.setData(data);
                            mHandler.obtainMessage(34).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("id",id);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        InvoiceListItem invoiceListItem = data.get(position);
        Intent intent = new Intent();
        intent.putExtra("inv_id",invoiceListItem);
        setResult(33,intent);
        finish();
    }
}
